package com.mzxy.mztopline.framgent;

import android.accessibilityservice.AccessibilityService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itheima.PullToRefreshView;
import com.mzxy.mztopline.R;
import com.mzxy.mztopline.adapter.AdBannerAdapter;
import com.mzxy.mztopline.adapter.HomeListAdapter;
import com.mzxy.mztopline.bean.NewsBean;
import com.mzxy.mztopline.utils.Contsant;
import com.mzxy.mztopline.utils.JsonParse;
import com.mzxy.mztopline.utils.UtilsHelper;
import com.mzxy.mztopline.view.ViewPagerIndicator;
import com.mzxy.mztopline.view.WrapRecyclerView;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {


    private PullToRefreshView mPullToRefreshView;
    private WrapRecyclerView recycleView;
    public static final int REFRESH_DELAY = 1000;
    private ViewPager adPager = new ViewPager(getContext());         //广告
    private ViewPagerIndicator vpi;  //小圆点
    private TextView tvAdName;        //广告名称
    private View adBannerLay;         //广告条容器
    private AdBannerAdapter ada; //适配器
    public static final int MSG_AD_SLID = 1;  //广告自动滑动
    public static final int MSG_AD_OK = 2;    //获取广告数据
    public static final int MSG_NEWS_OK = 3; //获取新闻数据
    private MHandler mHandler;                 //事件捕获
    private LinearLayout ll_python;
    private HomeListAdapter adapter;
    private RelativeLayout rl_title_bar;
    private OkHttpClient okHttpClient;
    private AdBannerAdapter adBannerAdapter;
    private List<NewsBean> data;
    private AccessibilityService context;


    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
//        View view = inflater.inflate(R.layout.fragment_home, container, false);

        mHandler = new MHandler();
        okHttpClient  = new OkHttpClient();
        View view = initview(inflater, container);


        getAdData();
        getNewsData();

        return view;
    }

    private void getNewsData() {
        final Request request = new Request.Builder().url(Contsant.WEB_SITE + Contsant.REQUEST_NEWS_URL).build();
        Call call = okHttpClient.newCall(request);
        //开启异步线程访问网络
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request arg0, IOException arg1) {

            }

            @Override
            public void onResponse(Response response) throws  IOException {
                String res= response.body().string();

                Message msg = new Message();
                msg.what = MSG_NEWS_OK;
                msg.obj = res;

                mHandler.sendMessage(msg);

            }
        });

    }

    private void getAdData() {

        Request request = new Request.Builder().url(Contsant.WEB_SITE + Contsant.REQUEST_AD_URL).build();
        Call call = okHttpClient.newCall(request);
        //开启异步线程访问网络
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request arg0, IOException arg1) {

            }

            @Override
            public void onResponse(Response response) throws  IOException {
                    String res= response.body().string();
                    data = JsonParse.getInstance().getAdList(res);
                    adBannerAdapter.setData(data);
                    vpi.setCount(data.size());
                    vpi.setCurrentPostion(0);

            }
        });

    }

    private View initview(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        View headview = inflater.inflate(R.layout.head_view,container,false);

        recycleView = view.findViewById(R.id.recycler_view);
        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        mPullToRefreshView = view.findViewById(R.id.pull_to_refresh);


        adapter = new HomeListAdapter(getContext());
        recycleView.setAdapter(adapter);
        recycleView.addHeaderView(headview);

        adBannerLay = headview.findViewById(R.id.adbanner_layout);
        vpi = headview.findViewById(R.id.advert_indicator);
        adPager = headview.findViewById(R.id.slidingAdvertBanner);
        tvAdName = headview.findViewById(R.id.tv_advert_title);


        adBannerAdapter  = new AdBannerAdapter(getFragmentManager());
        //adBannerAdapter.setData(data);
        adPager.setAdapter(adBannerAdapter);


        adPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (data != null && data.size()>0){
                    NewsBean nb = data.get(position % data.size());
                    tvAdName.setText(nb.getNewsName());
                    vpi.setCount(data.size());
                    vpi.setCurrentPostion(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

        });
        mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {

                mPullToRefreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullToRefreshView.setRefreshing(false);

                    }
                }, REFRESH_DELAY);

            }
        });
        resetSize();
        return view;
    }

    public class MHandler extends Handler {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case MSG_AD_SLID:

                    break;
                case MSG_AD_OK:
                    if (msg.obj != null) {
                        String adResult = (String) msg.obj;
                        data = JsonParse.getInstance().
                                getAdList(adResult);
                        if (data != null) {
                            if (data.size() > 0) {
                                adBannerAdapter.setData(data);
                                tvAdName.setText(data.get(0).getNewsName());
                                vpi.setCount(data.size());
                                vpi.setCurrentPostion(0);
                            }
                        }
                    }
                    break;
                case MSG_NEWS_OK:
                    if (msg.obj != null) {
                        String adResult = (String) msg.obj;
                        List<NewsBean> data = JsonParse.getInstance().
                                getAdList(adResult);
                        Log.d("yidong","data:"+(data == null? "null":data.size()));
                        if (data != null) {
                            if (data.size() > 0) {
                                //TODO
                                adapter.setData(data);

                            }
                        }
                    }
                    break;
            }
        }
    }
    /**
     * 计算控件大小
     */
    private void resetSize() {
        int sw = UtilsHelper.getScreenWidth(getActivity(), context);
        int adLheight = sw / 2; //广告条高度
        ViewGroup.LayoutParams adlp = adBannerLay.getLayoutParams();
        adlp.width = sw;
        adlp.height = adLheight;
        adBannerLay.setLayoutParams(adlp);
    }


}
